﻿/*
 * @author: wizardc
 */

using System;
using Dou.Resource;
using UnityEngine;
using Object = UnityEngine.Object;

namespace Dou.UI
{
    /// <summary>
    /// 该工具类为 UI 框架对接资源加载框架，如果需要切换其它的资源加载框架，只需要修改该工具类即可
    /// </summary>
    public static class UIAssetUtil
    {
        private static bool _resLoaded = false;
        
        private static Texture2D _transparentTex;
        private static Sprite _transparentSprite;
        private static Texture2D _whiteTex;
        private static Sprite _whiteSprite;
        private static Material _grayMat;

        private static void ResLoad()
        {
            if (!_resLoaded)
            {
                _resLoaded = true;
                
                _transparentTex = Resources.Load<Texture2D>("Image_Transparent");
                _transparentSprite = Resources.Load<Sprite>("Image_Transparent");
                _whiteTex = Resources.Load<Texture2D>("Image_White");
                _whiteSprite = Resources.Load<Sprite>("Image_White");
                _grayMat = Resources.Load<Material>("UIGray");
            }
        }

        public static Texture2D transparentTex
        {
            get
            {
                ResLoad();
                return _transparentTex;
            }
        }

        public static Sprite transparentSprite
        {
            get
            {
                ResLoad();
                return _transparentSprite;
            }
        }

        public static Texture2D whiteTex
        {
            get
            {
                ResLoad();
                return _whiteTex;
            }
        }

        public static Sprite whiteSprite
        {
            get
            {
                ResLoad();
                return _whiteSprite;
            }
        }

        public static Material grayMat
        {
            get
            {
                ResLoad();
                return _grayMat;
            }
        }

        /// <summary>
        /// 加载资源，内部引用加 1
        /// </summary>
        public static void LoadObject(string path, Action<string, Object> callback, bool isAsync = true, Type type = null)
        {
            if (type == null)
            {
                type = typeof(Object);
            }
            if (isAsync)
            {
                AssetManager.instance.LoadAsset(path, type, obj =>
                {
                    callback?.Invoke(path, obj);
                });
            }
            else
            {
                AssetManager.instance.LoadAssetSync(path, type, obj =>
                {
                    callback?.Invoke(path, obj);
                });
            }
        }

        /// <summary>
        /// 释放资源，内部引用减 1
        /// </summary>
        public static bool ReleaseObject(string path)
        {
            AssetManager.instance.UnloadAsset(path);
            return true;
        }
    }
}
